﻿using SXICE.Core.Configs;
using SXICE.Core.Helpers;
using SXICE.Core.Infrastructure;
using SXICE.Service.Models;
using System;

namespace SXICE.Service.Utilities
{
    /// <summary>
    /// 验证码存储器
    /// </summary>
    public class CaptchaStorage
    {
        /// <summary>
        /// 缓存
        /// </summary>
        private static readonly ICacheBase cache;
        /// <summary>
        /// 全局配置
        /// </summary>
        private static readonly GlobalConfigs globalConfigs;

        static CaptchaStorage()
        {
            cache = RuntimeHelper.Resolve<IDistributedCache>();
            globalConfigs = RuntimeHelper.Resolve<GlobalConfigs>();
        }

        /// <summary>
        /// 保存验证码
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="captcha">要保存的验证码</param>
        public static void SetCaptcha(string key, string captcha)
        {
            cache.Set(key, new CaptchaModel
            {
                Captcha = captcha,
                Expiration = DateTime.Now.AddMinutes(globalConfigs.MsgAliveMinutes),
                ReSendTime = DateTime.Now.AddMinutes(globalConfigs.ReSendMinutes)
            }, absoluteExpiration: DateTime.Now.AddMinutes(globalConfigs.MsgAliveMinutes));
        }

        /// <summary>
        /// 获取验证码对象
        /// </summary>
        /// <param name="key">键</param>
        /// <returns>验证码对象</returns>
        public static CaptchaModel GetCaptcha(string key)
        {
            cache.TryGet<CaptchaModel>(key, out var captcha);
            return captcha;
        }

        /// <summary>
        /// 移除
        /// </summary>
        /// <param name="key">要移除的键</param>
        public static void Remove(string key)
        {
            cache.Remove(key);
        }
    }
}
